package org.jsbd.boss.common;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class RetentPayConfigUtils {

	public static int[] random(int total) {
		int dom = getActualMaximum(new Date());
		int flag = 0;
		if (total > dom) {
			flag = dom - 1;
		} else {
			flag = total - 1;
		}

		int max = total - 1;
		int min = 1;
		Random random = new Random();

		int[] arr = new int[flag];
		for (int i = 0; i < flag; i++) {
			int s = random.nextInt(max) % (max - min + 1) + min;
			arr[i] = s;
		}
		sort(arr, 0, arr.length - 1);

		int[] arr_new = new int[flag + 1];
		for (int i = 0; i < flag; i++) {
			if (i == 0) {
				arr_new[i] = arr[i] - 0;
				continue;
			}
			arr_new[i] = arr[i] - arr[i - 1];
		}

		int sum = sum(arr_new);
		arr_new[flag] = total - sum;
		return arr_new;
	}

	public static void sort(int[] a, int low, int high) {
		int start = low;
		int end = high;
		int key = a[low];

		while (end > start) {
			while (end > start && a[end] >= key)
				end--;
			if (a[end] <= key) {
				int temp = a[end];
				a[end] = a[start];
				a[start] = temp;
			}
			while (end > start && a[start] <= key)
				start++;
			if (a[start] >= key) {
				int temp = a[start];
				a[start] = a[end];
				a[end] = temp;
			}
		}
		if (start > low)
			sort(a, low, start - 1);
		if (end < high)
			sort(a, end + 1, high);
	}

	public static int sum(int[] a) {
		int sum = 0;
		for (int i = 0; i < a.length; i++) {
			sum += a[i];
		}
		return sum;
	}

	public static int getActualMaximum(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
	}
	
	public static int getDayOfMonth(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.get((Calendar.DAY_OF_MONTH));
	}

	public static List<Integer> getDays(int num) {
		List<Integer> arr = new ArrayList<Integer>();
		List<Integer> arr_new = new ArrayList<Integer>();
		for (int i = 1; i <= 31; i++) {
			arr.add(i);
		}

		int dom = getActualMaximum(new Date());
		if (num >= dom) {
			return arr;
		}

		Random rand = new Random();
		for (int i = 0; i < num; i++) {
			Integer candidate = arr.get(rand.nextInt(arr.size()));
			arr_new.add(candidate);
			arr.remove(candidate);
		}
		return arr_new;
	}

}
